/*
 * Copyright 2019-present the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.consul.discovery.reactive;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient;
import org.springframework.cloud.consul.ConsulClient;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryClient;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;

/**
 * Consul version of {@link ReactiveDiscoveryClient}.
 *
 * @author Tim Ysewyn
 * @author Chris Bono
 */
public class ConsulReactiveDiscoveryClient implements ReactiveDiscoveryClient {

	private static final Logger logger = LoggerFactory.getLogger(ConsulReactiveDiscoveryClient.class);

	private final ConsulClient client;

	private final ConsulDiscoveryProperties properties;

	// TODO: implement ReactiveConsulClient to remove the need for subscribeOn()
	private final ConsulDiscoveryClient blockingClient;

	public ConsulReactiveDiscoveryClient(ConsulClient client, ConsulDiscoveryProperties properties) {
		this.client = client;
		this.properties = properties;
		blockingClient = new ConsulDiscoveryClient(client, properties);
	}

	@Override
	public String description() {
		return "Spring Cloud Consul Reactive Discovery Client";
	}

	@Override
	public Flux<ServiceInstance> getInstances(String serviceId) {
		return Flux.defer(() -> {
			List<ServiceInstance> instances = blockingClient.getInstances(serviceId);
			return Flux.fromIterable(instances);
		}).onErrorResume(exception -> {
			logger.error("Error getting instances from Consul.", exception);
			return Flux.empty();
		}).subscribeOn(Schedulers.boundedElastic());
	}

	@Override
	public Flux<String> getServices() {
		return Flux.defer(() -> {
			List<String> services = blockingClient.getServices();
			return services == null ? Flux.empty() : Flux.fromIterable(services);
		}).onErrorResume(exception -> {
			logger.error("Error getting services from Consul.", exception);
			return Flux.empty();
		}).subscribeOn(Schedulers.boundedElastic());
	}

	@Override
	public int getOrder() {
		return properties.getOrder();
	}

}
